package com.retailshop.shopuser.schedule;

import com.retailshop.shopuser.entity.UserNo;
import com.retailshop.shopuser.service.UserNoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class StatisticaloPulationTask {

    int total = 0;
    @Autowired
    UserNoService userNoService;

    @Scheduled(cron = "0 32 21 * * ?")
    public void updateUserNoSharerTotal() {
        List<UserNo> userNoList = userNoService.selectList();
        int userNoId = 0;
        for (int i = 0; i < userNoList.size(); i++) {
            userNoId = userNoList.get(i).getId();
            total = statsShareUserNo(userNoId);
            UserNo userNo = new UserNo();
            userNo.setId(userNoId);
            userNo.setSharerTotal(total);
            int row = userNoService.updatSharerTotal(userNo);
        }
    }


    public int statsShareUserNo(int userNoId) {
        if (userNoId != 0) {

            List<Integer> list = new ArrayList<>();

            List<UserNo> userNoList = getShare(userNoId);

            if (userNoList == null || userNoList.size() == 0) {
                return 0;
            }

            for (int i = 0; i < userNoList.size(); i++) {
                list.add(userNoList.get(i).getId());
            }

            getcount(list);//


            return total;

        } else {
            return 0;
        }

    }


    public void getcount(List<Integer> list) {

        List<Integer> list1 = new ArrayList<>();//里面
        List<Integer> list2 = new ArrayList<>();//外面

        List<UserNo> userNoList1 = null;

        if (list.size() == 0) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {

            System.out.println("----->" + list.size() + "id==" + list.get(i));

            total++;
            userNoList1 = getShare(list.get(i));
            if (userNoList1 == null || userNoList1.size() == 0) {
                continue;
            }


            for (int k = 0; k < userNoList1.size(); k++) {

                int Id = userNoList1.get(k).getId();
                list1.add(Id);
                System.out.println("第一层：" + Id);
            }


        }

        //第二层：数据
        for (int m = 0; m < list1.size(); m++) {
            int s = list1.get(m);
            list2.add(s);

        }
        System.out.println("list2:" + list2.size());

        getcount(list2);


    }


    public List<UserNo> getShare(int userNoId) {

        List<UserNo> userNoList = userNoService.getReCommender(userNoId);
        if (userNoList == null) {
            return null;
        }

        return userNoList;
    }

}
